package com.zzz.friend.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.zzz.common.core.constants.CacheConstants;
import com.zzz.common.core.constants.Constants;
import com.zzz.common.core.enums.ExamListType;
import com.zzz.common.redis.service.RedisService;
import com.zzz.friend.domain.exam.Exam;
import com.zzz.friend.domain.exam.dto.ExamQueryDTO;
import com.zzz.friend.domain.exam.vo.ExamVO;
import com.zzz.friend.mapper.exam.ExamMapper;
import com.zzz.friend.mapper.exam.UserExamMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @BelongsProject: oj-project
 * @BelongsPackage: com.zzz.friend.manager
 * @Author: zhai
 * @CreateTime: 2025-11-01  16:04
 * @Description: TODO
 * @Version: 1.0
 */
@Slf4j
@Component
public class ExamCacheManager {
    @Autowired
    private RedisService redisService;

    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private UserExamMapper userExamMapper;

    /**
     * @description: 获取竞赛列表的长度(历史列表或者是未完赛列表)
     * @author: zhai
     * @date:  16:05
     * @param: [examListType, userId]
     * @return: java.lang.Long
     **/
    public Long getExamListSize(Integer examListType, Long userId) {
        String examListKey = getExamListKey(examListType, userId);
        return redisService.getListSize(examListKey);
    }

    /**
     * @description: 获取竞赛题目列表的长度(赛题个数)
     * @author: zhai
     * @date: 2025/11/1 18:53
     * @param: [examId]
     * @return: java.lang.Long
     **/
    public Long getExamQuestionListSize(Long examId) {
        String examQuestionListKey = getExamQuestionListKey(examId);
        return redisService.getListSize(examQuestionListKey);
    }

    /**
     * @description: 从redis中获取竞赛列表
     * @author: zhai
     * @date: 2025/11/1 18:53
     * @param: [examListType]
     * @return: java.util.List<com.zzz.friend.domain.exam.vo.ExamVO>
     **/
    public List<ExamVO> getExamVOList(ExamQueryDTO examQueryDTO, Long userId) {
        int start = (examQueryDTO.getPageNum() - 1) * examQueryDTO.getPageSize();
        int end = start + examQueryDTO.getPageSize() - 1; //下标需要 -1
        log.info("判断从哪个列表中获取数据");
        String examListKey = getExamListKey(examQueryDTO.getType(), userId);
        List<Long> examIdList = redisService.getCacheListByRange(examListKey, start, end, Long.class);
        List<ExamVO> examVOList = assembleExamVOList(examIdList);
        if (CollectionUtil.isEmpty(examVOList)) {
            log.info("当前redis中没有数据");
            //说明redis中数据可能有问题 从数据库中查数据并且重新刷新缓存
            examVOList = getExamListByDB(examQueryDTO, userId); //从数据库中获取数据
            refreshCache(examQueryDTO.getType(), userId);
        }
        return examVOList;
    }

    /**
     * @description: 刷新缓存
     * @author: zhai
     * @date:  16:05
     * @param: [type, userId]
     * @return: void
     **/
    public void refreshCache(Integer examListType, Long userId) {
        List<Exam> examList = new ArrayList<>();
        if (ExamListType.EXAM_UN_FINISH_LIST.getValue().equals(examListType)) {
            //查询未完赛的竞赛列表
            examList = examMapper.selectList(new LambdaQueryWrapper<Exam>()
                    .select(Exam::getExamId, Exam::getTitle, Exam::getStartTime, Exam::getEndTime)
                    .gt(Exam::getEndTime, LocalDateTime.now())
                    .eq(Exam::getStatus, Constants.TRUE)
                    .orderByDesc(Exam::getCreateTime));
        } else if (ExamListType.EXAM_HISTORY_LIST.getValue().equals(examListType)) {
            //查询历史竞赛
            examList = examMapper.selectList(new LambdaQueryWrapper<Exam>()
                    .select(Exam::getExamId, Exam::getTitle, Exam::getStartTime, Exam::getEndTime)
                    .le(Exam::getEndTime, LocalDateTime.now())
                    .eq(Exam::getStatus, Constants.TRUE)
                    .orderByDesc(Exam::getCreateTime));
        } else if (ExamListType.USER_EXAM_LIST.getValue().equals(examListType)) {
            List<ExamVO> examVOList = userExamMapper.selectUserExamList(userId);
            examList = BeanUtil.copyToList(examVOList, Exam.class);
        }
        if (CollectionUtil.isEmpty(examList)) {
            return;
        }

        Map<String, Exam> examMap = new HashMap<>();
        List<Long> examIdList = new ArrayList<>();
        for (Exam exam : examList) {
            examMap.put(getDetailKey(exam.getExamId()), exam);
            examIdList.add(exam.getExamId());
        }
        redisService.multiSet(examMap);  //刷新详情缓存
        redisService.deleteObject(getExamListKey(examListType, userId));
        redisService.rightPushAll(getExamListKey(examListType, userId), examIdList);      //刷新列表缓存
    }

    /**
     * @description: 添加用户竞赛缓存
     * @author: zhai
     * @date: 2025/11/5 20:07
     * @param: []
     * @return: void
     **/
    public void addUserExamCache(Long userId, Long examId) {
        String userExamListKey = getUserExamListKey(userId);
        redisService.leftPushForList(userExamListKey, examId);
    }

    /**
     * @description: 获取用户竞赛列表缓存的key
     * @author: zhai
     * @date: 2025/11/5 20:07
     * @param: [userId]
     * @return: java.lang.String
     **/
    private String getUserExamListKey(Long userId) {
        return CacheConstants.USER_EXAM_LIST + userId;
    }

    /**
     * @description: 从数据库中获取数据并且存储在缓存中
     * @author: zhai
     * @date:  16:05
     * @param: [examQueryDTO]
     * @return: java.util.List<com.zzz.friend.domain.exam.vo.ExamVO>
     **/
    private List<ExamVO> getExamListByDB(ExamQueryDTO examQueryDTO, Long userId) {
        log.info("从数据库中获取数据");
        PageHelper.startPage(examQueryDTO.getPageNum(), examQueryDTO.getPageSize());
        if (ExamListType.USER_EXAM_LIST.getValue().equals(examQueryDTO.getType())) {
            //查询我的竞赛列表
            return userExamMapper.selectUserExamList(userId);
        } else {
            //查询C端的竞赛列表
            return examMapper.selectExamList(examQueryDTO);
        }
    }

    /**
     * @description: 获取竞赛列表，通过id获取到数据
     * @author: zhai
     * @date:  16:05
     * @param: examIdList 竞赛ID列表
     * @return: java.util.List<com.zzz.friend.domain.exam.vo.ExamVO>
     **/
    private List<ExamVO> assembleExamVOList(List<Long> examIdList) {
        log.info("获取到examId列表：{}", examIdList);
        if (CollectionUtil.isEmpty(examIdList)) {
            // 说明redis中没有数据, 需要重新从数据库中拿去并存储在缓存中
            log.error("redis中没有数据");
            return null;
        }
        // 我们在这边设计的时候就是使用列表存储：e:d:examId因此该列表内存储的就是竞赛的ID
        List<String> detailKeyList = new ArrayList<>();
        CollUtil.removeNull(examIdList);
        for (Long examId : examIdList) {
            detailKeyList.add(getDetailKey(examId));
        }
        List<ExamVO> examVOList = redisService.multiGet(detailKeyList, ExamVO.class);
        if (CollectionUtil.isEmpty(examVOList) || examVOList.size() != examIdList.size()) {
            // 说明redis中的数据有问题
            log.error("redis中的数据有问题");
            return null;
        }
        log.info("获取到examVO列表：{}", examVOList);
        return examVOList;
    }

    /**
     * @description: 根据竞赛列表类型和用户ID获取对应的缓存key
     * @author: zhai
     * @date:  16:05
     * @param: examListType 竞赛列表类型 1-未完成列表 2-历史列表 其他-用户竞赛列表
     * @return: java.lang.Long
     **/
    private String getExamListKey(Integer examListType, Long userId) {
        if (ExamListType.EXAM_UN_FINISH_LIST.getValue().equals(examListType)) {
            return CacheConstants.EXAM_UNFINISHED_LIST;
        } else if (ExamListType.EXAM_HISTORY_LIST.getValue().equals(examListType)) {
            return CacheConstants.EXAM_HISTORY_LIST;
        } else {
            // 如果是用户竞赛列表，则返回对应的缓存key也就是: u:e:l:userId
            return CacheConstants.USER_EXAM_LIST + userId;
        }
    }

    /**
     * @description: 根据竞赛列表类型和用户ID获取对应的缓存key
     * @author: zhai
     * @date:  16:05
     * @param: examListType 竞赛列表类型 1-未完成列表 2-历史列表 其他-用户竞赛列表
     * @return: java.lang.Long
     **/
    private String getExamListKey(Integer examListType) {
        if (ExamListType.EXAM_UN_FINISH_LIST.getValue().equals(examListType)) {
            return CacheConstants.EXAM_UNFINISHED_LIST;
        } else if (ExamListType.EXAM_HISTORY_LIST.getValue().equals(examListType)) {
            return CacheConstants.EXAM_HISTORY_LIST;
        } else {
            return CacheConstants.EXAM_UNFINISHED_LIST;
        }
    }

    /**
     * @description: 获取竞赛详情的缓存key
     * @author: zhai
     * @date:  16:05
     * @param: [examId]
     * @return: java.lang.String
     **/
    private String getDetailKey(Long examId) {
        return CacheConstants.EXAM_DETAIL + examId;
    }

    /**
     * @description: 获取竞赛题目列表的key
     * @author: zhai
     * @date: 2025/11/1 18:53
     * @param: [examId]
     * @return: java.lang.String
     **/
    private String getExamQuestionListKey(Long examId) {
        return CacheConstants.EXAM_QUESTION_LIST + examId;
    }

    private String getExamRankList(Long examId) {
        return CacheConstants.EXAM_RANK_LIST + examId;
    }
}
